<?php


namespace Pay\Controller;

use Think\Controller;


class IndexController extends Controller
{
    
    public function pay()
    {


        // header("Content-type: text/html; charset=utf-8");
        // if(IS_POST){
        //     //查出总账单
        //     foreach (I('item') as $k => $v) {
        //         //根据账单生成订单
        //         $con['item'] = $v;
        //         $bill =M('core_pay_bill_view')->where($con)->select();
        //         $a = explode(' ',microtime());
        //         $order_id = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));
        //         $data['order_id'] = $order_id;
        //         $data['order_detail'] = $bill['detail'];
        //         //明细拼接
        //         foreach ($bill as $key => $value) {
        //             if($value['item_c']!=0){
        //                 $data['order_detail'].=';'.$value['ctitle'].':'.$value['amount'];
        //             }else{
        //                 $data['unit'] = $value['unit'];
        //                 $data['bill_id'] = $value['id'];
        //                 $data['order_name'] = $value['ititle'];
        //                 $data['order_detail'].=$value['detail'];
        //             }
        //         }
        //         $data['amount'] = I('total');
        //         $data['status'] = 0;
        //         $data['create_time'] = time();
        //         $SIGN_ARR = array('BUSINESS'=>'BankABC370300','LINKTYPE'=>1,'MERCHANT'=>'MYGS0218100254','ORDERAMOUNT'=>$data['amount'],'ORDERDATE'=>date('Y-m-d',$data['create_time']),'ORDERID'=>$data['order_id'],'ORDERNAME'=>$data['order_name'],'ORDERTIME'=>date('H:i:s',$data['create_time']),'REMARK'=>$bill[0]['qq'],'RETURNURL'=>'http://192.168.2.111/dakeyey/index.php?s=/Pay/PostPay/payReturn');
        //         $data['sign'] = $this->encrypt(implode('|', $SIGN_ARR),'E','MYGS0218100254');
        //         $SIGN_ARR['SIGN'] = $data['sign'];
        //         $odata[] = $data;
        //     }
        //         $result = M('core_pay_order')->addAll($odata);
        //     //生成流水
        //     $pdata['order_id'] = $order_id;
        //     $pdata['amount'] = I('total');
        //     $flow_id = $this->create_flow($pdata);
        //     //去支付
        //    $MERCHANTID='MYGS0218100254';// 商户编号

        //    $POSID = '10001010'; // 商户柜台代码

        //    $ORDERID= $flow_id; // 支付流水号
        //    $PROINFO= $this->escape('账单'); // 商品信息

        //    $PAYMENT = I('total'); // 付款金额
        //    $REMARK1 = $this->escape("优惠活动"); // 备注一
        //    $LINKTYPE =2; // 客户端接入方式
        //    //----传输信息-------------
        //    $PERKEY = 'zibodake'; //私钥

        //    $dopayURL="http://dopay.epayol.com/index.php/Home/Dopay/pay";
        //    //发送字符串
        //    $postMsg='MERCHANTID='.$MERCHANTID.'&POSID='.$POSID.'&ORDERID='.$ORDERID.'&PROINFO='.$PROINFO.'&PAYMENT='.$PAYMENT.'&REMARK1='.$REMARK1.'&PAYIP='.get_client_ip().'&LINKTYPE='.$LINKTYPE;    

        //    $URL = $dopayURL . '?' .$postMsg. '&SIGN=' . MD5 ($postMsg . '&PERKEY=' . $PERKEY) ;
        //    header("Location:".$URL);
        // }else{
        //     $map['uid'] = $_SESSION['oc_home']['uid'];
        //     $map['status'] = 1;
        //     $map['pay_state'] = 0;
        //     $map1['item_c'] = array('eq',0);
        //     $map2['item_c'] = array('neq',0);
        //     $bill = M('core_pay_bill_view')->where($map)->where($map1)->select();
        //     foreach ($bill as $key => $value) {
        //        $bill[$key]['zamount'] = M('core_pay_bill_view')->where($map)->where('item = '.$value['item'].' and setstate = 1 ')->sum('amount');
        //        $bill[$key]['sub'] = M('core_pay_bill_view')->where($map)->where($map2)->where('item = '.$value[''])->select();
        //     }
        //     //必选金额
        //     $btotal = M('core_pay_bill_view')->where($map)->where($map2)->where('setstate = 1')->sum('amount');
        //     //全选金额
        //     $atotal = M('core_pay_bill_view')->where($map)->where($map2)->sum('amount');
           
        //     $this->assign('bill',$bill);
        //     $this->assign('total',(int)$btotal);
        //     $this->assign('atotal',(int)$atotal);
        //     $this->display();
        // }
        
   
        $map['uid']=$_SESSION['oc_home']['uid'];
        $map['unit']=$_SESSION['oc_home']['unit'];
        $map['status'] = array('not in','-1,2');
        $list = M('core_pay_bill_view')->where($map)->group('item')->select();
        $this->assign('list',$list);
        
        $this->display();
    }
    public function subpay()
    {
       
        $map['uid']=$_SESSION['oc_home']['uid'];
        $map['batch'] =I('batch');
        $map['unit']=$_SESSION['oc_home']['unit'];
        $map['pay_state'] = 0;
        $map['status'] = array('not in','-1,2');
        $list = M('core_pay_bill_view')->where($map)->select();
        $amount=M('core_pay_bill_view')->where($map)->sum('amount');
        $this->assign('slist',$list);
        $this->assign('amount',$amount);

        $this->display();
    }
    //生成流水
    // public function create_flow($data)
    // {
    //     $a = explode(' ',microtime());
    //     $data['flow_id'] = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));
    //     $data['unit'] = $_SESSION['oc_home']['unit'];
    //     $data['create_time'] = time();
    //     $result = M('core_pay_flow')->add($data);
    //     return $data['flow_id'];
    // }
    // public function pay()
    // {
    //     header("Content-type: text/html; charset=utf-8");
    //     if(IS_POST){
    //         //查出总账单
    //         $con['item'] = I('item');
    //         $bill =M('core_pay_bill_view')->where($con)->select();
    //         $a = explode(' ',microtime());
    //         $order_id = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));
    //         $data['order_id'] = $order_id;
    //         $data['order_detail'] = $bill['detail'];
    //         foreach ($bill as $key => $value) {
    //             if($value['item_c']!=0){
    //                 $data['order_detail'].=';'.$value['ctitle'].':'.$value['amount'];
    //             }else{
    //                 $data['unit'] = $value['unit'];
    //                 $data['bill_id'] = $value['id'];
    //                 $data['order_name'] = $value['ititle'];
    //                 $data['order_detail'].=$value['detail'];
    //             }
    //         }
    //         $data['amount'] = I('total');
    //         $data['status'] = 0;
    //         $data['create_time'] = time();
    //         $SIGN_ARR = array('BUSINESS'=>'BankABC370300','LINKTYPE'=>1,'MERCHANT'=>'MYGS0218100254','ORDERAMOUNT'=>$data['amount'],'ORDERDATE'=>date('Y-m-d',$data['create_time']),'ORDERID'=>$data['order_id'],'ORDERNAME'=>$data['order_name'],'ORDERTIME'=>date('H:i:s',$data['create_time']),'REMARK'=>$bill[0]['qq'],'RETURNURL'=>'http://192.168.2.111/dakeyey/index.php?s=/Pay/PostPay/payReturn');

    //         $data['sign'] = $this->encrypt(implode('|', $SIGN_ARR),'E','MYGS0218100254');
    //         $SIGN_ARR['SIGN'] = $data['sign'];
    //         $result = M('core_pay_order')->add($data);
    //         if($result){
    //             echo "<script>";
    //             echo"alert('订单添加成功');";
    //             echo "window.location.href='./index.php?s=/Pay/PostPay/index&order=".serialize($SIGN_ARR)."'; ";
    //             // echo "window.location.href='http://192.168.2.234/index.php?s=/pay/dopay/index.html'; ";
    //             echo"</script>";
    //         }
    //     }else{
    //         $map['uid'] = $_SESSION['oc_home']['uid'];
    //         $map['status'] = 1;
    //         $map['pay_state'] = 0;
    //         $map1['item_c'] = array('eq',0);
    //         $map2['item_c'] = array('neq',0);
    //         $bill = M('core_pay_bill_view')->where($map)->where($map1)->select();
    //         foreach ($bill as $key => $value) {
    //            $bill[$key]['zamount'] = M('core_pay_bill_view')->where($map)->where('item = '.$value['item'].' and setstate = 1 ')->sum('amount');
    //            $bill[$key]['sub'] = M('core_pay_bill_view')->where($map)->where($map2)->select();
    //         }
    //         //必选金额
    //         $btotal = M('core_pay_bill_view')->where($map)->where($map2)->where('setstate = 1')->sum('amount');
    //         //全选金额
    //         $atotal = M('core_pay_bill_view')->where($map)->where($map2)->sum('amount');
           
    //         $this->assign('bill',$bill);
    //         $this->assign('total',(int)$btotal);
    //         $this->assign('atotal',(int)$atotal);
    //         $this->display();
    //     }
    // }

    //订单列表
    public function pays()
    {
        $map['uid'] = $_SESSION['oc_home']['uid'];
        $map['paystate'] =0;
        $map['status'] = array('not in','-1,2');
        $order =M('core_pay_order_view')->where($map)->select();
        $this->assign('order',$order);
        $this->display();
    }
    //添加订单，预览订单
    public function addorder()
    {

        $mon['uid']=$_SESSION['oc_home']['uid'];
        $mon['unit']=$_SESSION['oc_home']['unit'];
        $mon['order_name'] = trim(I('ititle'));
        $mon['paystate'] =0;
        $mon['status'] = array('not in','-1,2');
        $map['uid'] = $_SESSION['oc_home']['uid'];
        $map['paystate'] =0;
        $map['status'] = array('not in','-1,2');
        $aaa= M('core_pay_order')->where($mon)->select();
        if($aaa){

        $list =  M('core_pay_order')->where($map)->select();
        $this->assign('list',$list);
        }else{
           if(!I('ititle')) $this->error('订单名不能为空!');
            $data['uid']=$_SESSION['oc_home']['uid'];
            $data['unit']=$_SESSION['oc_home']['unit'];
            $a = explode(' ',microtime());
            $data['order_id'] = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));
            $data['order_name']=I('ititle');
            $detail= M('core_pay_bill_view')->where($map)->field('last_amount,ctitle,amount')->select();
            foreach ($detail as $key => $v) {
                $tmp .=$v['ctitle'].':'.$v['amount'].'，结余：'.$v['last_amount'].' ';
                $amount +=$v['amount'];
                $last_amount +=$v['last_amount'];
                $aa=$amount-$last_amount;
            }
            $data['order_detail'] = $tmp;
            $data['amount']=$aa;
            $data['paystate']=0;
            $data['status']=1;
            $data['create_time']=time();
            $result=M('core_pay_order')->add($data);
            if($result){
                $odata['order_id'] =$data['order_id'];
                
                $aamap['uid']=$_SESSION['oc_home']['uid'];
                $aamap['unit'] =$_SESSION['oc_home']['unit'];
                $aamap['batch'] =$_SESSION['batch'];
                $b = M('core_pay_bill')->where($aamap)->save($odata);
                $list =  M('core_pay_order')->where($map)->select();
                $this->assign('list',$list);
                }else{
                    $this->error('添加失败');
            }
        }
        $this->display();
    }
   
    //支付
    public function gopay()
    {       
        header("Content-type: text/html; charset=utf-8");
    
        $a = explode(' ',microtime());
        $data['flow_id'] = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));    //流水号
        $data['order_id'] = I('order_id');
        $data['amount'] = I('amount');
        $data['unit'] = $_SESSION['oc_home']['unit'];
        $data['create_time']=time();
        $data['paystate']=0;
        $data['state']=1;
        $result=M('core_pay_flow')->add($data);
        if($result){
        $aaa['unit'] =$_SESSION['oc_home']['unit'];
        $midpid=M('core_merchant')->where($aaa)->field('merchant_id,posid')->find();
       
        /*$MERCHANTID=$midpid['merchant_id'];// 商户编号
        $POSID = $midpid['posid']; // 商户柜台代码*/
      $MERCHANTID='CMKR0902010926';// 商户编号

      // $POSID = '10001010'; // 商户柜台代码
        $ORDERID= $data['flow_id']; // 支付流水号
        $PROINFO= $this->escape('账单'); // 商品信息
        $PAYMENT = I('amount'); // 付款金额
        $REMARK1 = $this->escape("优惠活动"); // 备注一
        $LINKTYPE =2; // 客户端接入方式
        //----传输信息-------------
        $PERKEY = 'zibodake'; //私钥
        $dopayURL="http://dopay.epayol.com/index.php/Home/Dopay/pay";
        //发送字符串
        $postMsg='MERCHANTID='.$MERCHANTID.'&POSID='.$POSID.'&ORDERID='.$ORDERID.'&PROINFO='.$PROINFO.'&PAYMENT='.$PAYMENT.'&REMARK1='.$REMARK1.'&PAYIP='.get_client_ip().'&LINKTYPE='.$LINKTYPE;    

        $URL = $dopayURL . '?' .$postMsg. '&SIGN=' . MD5 ($postMsg . '&PERKEY=' . $PERKEY) ;
        header("Location:".$URL);
            
        }else{
           $this->error('支付失败'); 
        }

        
    }        

    /*********************************************************************
      函数名称:encrypt
      函数作用:加密解密字符串
      使用方法:
      加密   :encrypt('str','E','nowamagic');
      解密   :encrypt('被加密过的字符串','D','nowamagic');
      参数说明:
      $string  :需要加密解密的字符串
      $operation:判断是加密还是解密:E:加密  D:解密
      $key   :加密的钥匙(密匙，商户号);
      $测试key   :
        商家号：CR6QYFO2HA
        商户号：XTPWLTTAKT86
    *********************************************************************/
      function encrypt($string,$operation,$key='')
      {
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++)
        {
          $rndkey[$i]=ord($key[$i%$key_length]);
          $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++)
        {
          $j=($j+$box[$i]+$rndkey[$i])%256;
          $tmp=$box[$i];
          $box[$i]=$box[$j];
          $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++)
        {
          $a=($a+1)%256;
          $j=($j+$box[$a])%256;
          $tmp=$box[$a];
          $box[$a]=$box[$j];
          $box[$j]=$tmp;
          $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D')
        {
          if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8))
          {
            return substr($result,8);
          }
          else
          {
            return'';
          }
        }
        else
        {
          return str_replace('=','',base64_encode($result));
        }
      }

    public function jiaofeipay()
    {
      $this->display();
    }
    public function DeanPaymentSummary()
    {
        if(I('nickname')){  
            $nickname = I('nickname');
            $map['nickname'] = array('like','%'.$nickname.'%');
            $this->assign('nickname',$nickname);
        }
        if(I('createtime')&&I('endDate')){
             $map['leave_date'] = array(between,array(strtotime(I('createtime')),strtotime(I('endDate'))));
        }
        if(I('class')){  
            $class = I('class');
            $map['class_id'] = array('like','%'.$class.'%');
            $this->assign('class',$class);
        }
        $map1['unit']=$_SESSION["oc_home"]['unit'];
        $map['group_id']=5;
        $map['item_c']=0;
        $map2['pay_state']=1;
        $map3['pay_state']=0;
        $map['unit_id']=$_SESSION["oc_home"]['unit'];
        $map['class_id']=$_SESSION["oc_home"]['class'];   
        $list=M('core_unit_paytype')->where($map1)->select();
        if($_SESSION['oc_home']['group']==6){
                $fy = M('core_unit')->where('pid='.$_SESSION['oc_home']['unit'])->getField('id',true);
                //查总园下面所有分园
                $map['unit_id'] = array('in',implode(',',$fy));
                
                $list=M('core_unit_paytype')->where($map)->select();
            }
            
        $data=M('core_unit')->where('id='.$_SESSION["oc_home"]['unit'])->select();
        $class=M('core_class')->where('unit='.$_SESSION["oc_home"]['unit'])->select();
        if($_SESSION['oc_home']['group']==6){
                $fy = M('core_unit')->where('pid='.$_SESSION['oc_home']['unit'])->getField('id',true);
                //查总园下面所有分园
                $map['unit'] = array('in',implode(',',$fy));
                $data = M('core_unit')->where('pid='.$_SESSION['oc_home']['unit'])->select();
                $class=M('core_class')->where($map)->select();
            }
        foreach ($list as $key => $value) {
            $leave=M('core_userinfo_view')->where($map)->select();
            $count=count($leave);
            $succ=M('core_pay_bill_tmp_view')->where($map)->where($map2)->count();
            $eroo=M('core_pay_bill_tmp_view')->where($map)->where($map3)->count();
            $like=$count-$succ;
            $list[$key]['weijiao']=$like;
            $list[$key]['yijiao']=$succ;
            }
        $this->assign('list',$list);
        $this->assign('data',$data);
        $this->assign('class',$class);
        $this->assign('count',$count);
        $this->display();
      
    }
    // --json传送中文字符串的解密编码escape函数

    public function unescape($str){

        $ret = '';

        $len = strlen($str);

        for ($i = 0; $i < $len; $i++){

            if ($str[$i] == '%' && $str[$i+1] == 'u'){

                $val = hexdec(substr($str, $i+2, 4));

                if ($val < 0x7f) $ret .= chr($val);

                else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));

                else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));

                $i += 5;

            }

            else if ($str[$i] == '%'){

                $ret .= urldecode(substr($str, $i, 3));

                $i += 2;

            }

            else $ret .= $str[$i];

        }

        return $ret;

    }

    // --json传送中文字符串的加密编码escape函数

    function escape($str) {

        preg_match_all ( "/[\xc2-\xdf][\x80-\xbf]+|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}|[\x01-\x7f]+/e", $str, $r );

        // 匹配utf-8字符，

        $str = $r [0];

        $l = count ( $str );

        for($i = 0; $i < $l; $i ++) {

            $value = ord ( $str [$i] [0] );

            if ($value < 223) {

                $str [$i] = rawurlencode ( utf8_decode ( $str [$i] ) );

                // 先将utf8编码转换为ISO-8859-1编码的单字节字符，urlencode单字节字符.

                // utf8_decode()的作用相当于iconv("UTF-8","CP1252",$v)。

            } else {

                $str [$i] = "%u" . strtoupper ( bin2hex ( iconv ( "UTF-8", "UCS-2", $str [$i] ) ) );

            }

        }

        return join ( "", $str );

    }
}